var currentData;

function queryParams(params) {
	$('#theform').serializeArray().forEach(function fn(v){
		params[v.name] = v.value;
	});
    return params;
}

function responseHandler(root) {
	$('#theader').html('表格 记录数:'+root.hits.total+', 搜索耗时:'+root.took+'ms, 分片:'+root._shards.successful +'/'+ root._shards.total);
	
	currentData = redrawByDayUnit(root);
	var index = $("input[name='GraphiIndex']:checked").val();
	redrawChart(index);
	return currentData;
}

function redrawByDayUnit(root){
	var aggField = '';
	var xAxis = {};
	
	aggField = 'search_engin';
	
	var r = [];
	root.aggregations['group_by@' + aggField + '@' + aggField].buckets.forEach(function (v){
		if(!( v.key in xAxis )){
			xAxis[v.key] = { 'Site':v.key };
		}
		
		$.extend( xAxis[v.key], {
			pv: v['sum@' + aggField + '@pv'].value,
			uv: v['sum@' + aggField + '@uv'].value,
			ip: v['sum@' + aggField + '@ip'].value,
			vv: v['sum@' + aggField + '@vv'].value,
			nv: v['sum@' + aggField + '@nv'].value,
			nvp: (v['sum@' + aggField + '@nv'].value / v['sum@' + aggField + '@uv'].value * 100).toFixed(2),
			bounce_rate: ((v['sum@' + aggField + '@bounce'].value / v['sum@' + aggField + '@vv'].value * 100).toFixed(2)),

			trunover: v['sum@' + aggField + '@trunover'].value,
			trunover_time: (v['sum@' + aggField + '@trunover_time_sum'].value / v['sum@' + aggField + '@trunover'].value).toFixed(0),
			trunover_seq: (v['sum@' + aggField + '@trunover_seq_sum'].value / v['sum@' + aggField + '@trunover'].value).toFixed(0),

			session_per_user: (v['sum@' + aggField + '@session_time_sum'].value / v['sum@' + aggField + '@session_count_sum'].value / 1000).toFixed(0),
			stay_per_user: (v['sum@' + aggField + '@stay_time_sum'].value / v['sum@' + aggField + '@stay_user_sum'].value).toFixed(0),
			pv_per_vv: (v['sum@' + aggField + '@pv'].value / v['sum@' + aggField + '@vv'].value).toFixed(2)
		})
	});
	
	for(var k in xAxis){
		r.push(xAxis[k])
	}
	
	v = root.aggregations["group_by@site_id@site_id"].buckets[0];
	var summaryrow = {};
	if (v === undefined){
		summaryrow = {
			pv: '-',
			uv: '-',
			ip: '-',
			vv: '-',
			nv: '-',
			nvp: '-',
			bounce_rate: '-',
			
			trunover: '-',
			trunover_time: '-',
			trunover_seq: '-',
			
			session_per_user: '-',
			stay_per_user: '-',
			pv_per_vv: '-'
		}
		
	} else {
		summaryrow = {
			pv: v['sum@site_id@pv'].value,
			uv: v['sum@site_id@uv'].value,
			ip: v['sum@site_id@ip'].value,
			vv: v['sum@site_id@vv'].value,
			nv: v['sum@site_id@nv'].value,
			nvp: (v['sum@site_id@nv'].value / v['sum@site_id@uv'].value * 100).toFixed(2),
			bounce_rate: ((v['sum@site_id@bounce'].value / v['sum@site_id@vv'].value * 100).toFixed(2)),

			trunover: v['sum@site_id@trunover'].value,
			trunover_time: (v['sum@site_id@trunover_time_sum'].value / v['sum@site_id@trunover'].value).toFixed(0),
			trunover_seq: (v['sum@site_id@trunover_seq_sum'].value / v['sum@site_id@trunover'].value).toFixed(0),

			session_per_user: (v['sum@site_id@session_time_sum'].value / v['sum@site_id@session_count_sum'].value / 1000).toFixed(0),
			stay_per_user: (v['sum@site_id@stay_time_sum'].value / v['sum@site_id@stay_user_sum'].value).toFixed(0),
			pv_per_vv: (v['sum@site_id@pv'].value / v['sum@site_id@vv'].value).toFixed(2)
		}
	}
	
	$('#summarytable').bootstrapTable('updateRow', { index: 0, row:summaryrow });
	
	return r;
}

function redrawChart(index){
	
	var indexName = "";
	
	if(index == 'uv') {
		indexName = '访客数（UV）';
			
	} else if(index == 'ip') {
		indexName = 'IP';
		
	} else if(index == 'vv') {
		indexName = '访问次数（VV）';
		
	} else if(index == 'nv') {
		indexName = '新访客数（NV）';
		
	} else if(index == 'nvp') {
		indexName = '新客率';
		
	} else if(index == 'bounce_rate') {
		indexName = '跳出率';
		
	} else if(index == 'trunover') {
		indexName = '下单数';
		
	} else if(index == 'trunover_time') {
		indexName = '平均下单时间';
		
	} else if(index == 'trunover_seq') {
		indexName = '平均下单步骤';
		
	} else if(index == 'session_per_user') {
		indexName = '平均会话时长(秒)';
		
	} else if(index == 'stay_per_user') {
		indexName = '平均访问时长';
		
	} else if(index == 'pv_per_vv') {
		indexName = '平均访问页面数';
		
	}  else {
		//pv
		index = 'pv';
		indexName = '浏览量（PV）';
	}
	
	var xAxisData = [];
	var data1 = [];
	
	currentData.forEach(function(v){
		xAxisData.push(v.Site);
		if (v[index] == '-')
			data1.push(0);
		else
			data1.push(v[index]);
	});
	
	option = {
	    title: {
	        text: indexName
	    },
	    tooltip: {},
	    xAxis: {
	        data: xAxisData,
	        silent: false,
	        splitLine: {
	            show: false
	        }
	    },
	    yAxis: {
	    },
	    series: [{
	        type: 'bar',
	        data: data1
	    }]
	};
	var myChart = echarts.init(document.getElementById('main'));
	myChart.setOption(option, true);
}

function idFormatter(value) {
	return '<button type="button" class="btn btn-info" onclick="toHistory(\''+value+'\')">查看历史趋势</button>';
}

function toHistory(value) {
	window.open( '/analytics/site.htm?qtype=source3&search_engin='+value+'&TimeDay=' + $('#TimeDay').val() + '&BranchId=' + $('#BranchId').val() );
}

function initTable(){
	
	$('#thetable').bootstrapTable('destroy');
	$('#thetable').bootstrapTable({
		showExport: true,
		url: '/analytics/source3.json',
		method: 'post',
		queryParams: queryParams,
		responseHandler: responseHandler,
		idField: 'Site',
		classes: 'table table-hover table-condensed',
		striped: true,
		dataShowExport: true,
		sortStable: true,
		pagination: true,
		columns: [
			{
		        field: 'Site',
		        sortable: true,
		        title: '搜索引擎'
		    }, {
		        field: 'Site',
		        title: '历史趋势',
		        sortable: true,
		        formatter: idFormatter
		    }, {
		        field: 'pv',
		        title: '浏览量（PV）',
		        sortable: true,
		        formatter: numt
		    }, {
		        field: 'uv',
		        title: '访客数（UV）',
		        sortable: true,
		        formatter: numt
		    }, {
		        field: 'ip',
		        title: 'IP',
		        formatter: numt
		    }, {
		        field: 'vv',
		        title: '访问次数（VV）',
		        sortable: true,
		        formatter: numt
		    }, {
		        field: 'nv',
		        title: '新访客数（NV）',
		        sortable: true,
		        formatter: numt
		    }, {
		        field: 'nvp',
		        title: '新客率',
		        sortable: true,
		        formatter: nump
		    }, {
		        field: 'bounce_rate',
		        title: '跳出率',
		        sortable: true,
		        formatter: nump
		    }, {
		        field: 'trunover',
		        title: '下单数',
		        sortable: true,
		        formatter: numt
		    }, {
		        field: 'trunover_time',
		        title: '平均下单时间',
		        sortable: true,
		        formatter: numts
		    }, {
		        field: 'trunover_seq',
		        title: '平均下单步骤',
		        sortable: true,
		        formatter: numt
		    }, {
		        field: 'session_per_user',
		        title: '平均会话时长',
		        sortable: true,
		        formatter: numts
		    }, {
		        field: 'stay_per_user',
		        title: '平均访问时长',
		        sortable: true,
		        formatter: numts
		    }, {
		        field: 'pv_per_vv',
		        title: '平均访问页面数',
		        sortable: true,
		        formatter: numt
		    }
		]
	});
	
}

function switchTable(){
	initTable();
}

$(document).ready(function () {

	$('#theform_commit').click(function (){
		switchTable();
	});
	
	$("#GraphiIndex").change(function() {
		redrawChart($(this).val());
	});
	
	switchTable();
	initDateRangePick($('#TimeDay'));
	
	$('#summarytable').bootstrapTable({
		data: [{
			pv: '-',
			uv: '-',
			ip: '-',
			vv: '-',
			nv: '-',
			nvp: '-',
			bounce_rate: '-',
			
			trunover: '-',
			trunover_time: '-',
			trunover_seq: '-',
			
			session_per_user: '-',
			stay_per_user: '-',
			pv_per_vv: '-'
		}]
	});
	
	$.ajax({
		url: '/analytics/branch.json', 
		type: 'POST', 
		data:{ type:'site' }, 
		dataType: 'json', 
		error: function(){
			alert('Error loading branch');
		}, 
		success: function(root){
			var control = $('#BranchId')
			control.find('option').remove().end();
			control.append('<option value="">全部</option>');
			var kv = {}
			root.aggregations['group_by@branch_id@branch_id'].buckets.forEach(function (v){
				if (v.key.length == 0) return;
				if (b2b_map !== undefined && b2b_map[v.key] !== undefined){
					kv[v.key] = b2b_map[v.key] + " ( pv:" + v['sum@branch_id@pv'].value + " )";
				} else {
		        	kv[v.key] = v.key + " ( pv:" + v['sum@branch_id@pv'].value + " )";
		        }
			});
			$.each(kv, function (k,v){	
				control.append($('<option>', { value : k, text: v }));
			});
		} 
	}); 
	
});
